package protocol

import (
	"os"

	"daxin.my/test-netserver/api"
	"daxin.my/test-netserver/protocol/dubbo"
	"daxin.my/test-netserver/protocol/grpc"
	"daxin.my/test-netserver/protocol/http"
)

const (
	// 环境变量
	HttpPort           = "HTTP_PORT"
	HttpServer2Address = "HTTP_SERVER_ADDRESS_2"

	GrpcPort          = "GRPC_PORT"
	GrpcServerAddress = "GRPC_SERVER_ADDRESS"

	DubboProvider = "CONF_PROVIDER_FILE_PATH"
	DubboLog      = "APP_LOG_CONF_FILE"
	DubboConsumer = "CONF_CONSUMER_FILE_PATH"

	// CLIENT KEY
	CLIENT_HTTP  = "http"
	CLIENT_GRPC  = "grpc"
	CLIENT_DUBBO = "dubbo"
)

func InitServer() {
	// 启动HTTP服务，不论是客户端角色还是服务端角色
	go http.StartHttpServer(os.Getenv(HttpPort), api.HttpClient)

	if grpcPort := os.Getenv(GrpcPort); grpcPort != "" {
		// 只有服务端配置端口才启动GRPC服务
		go grpc.StartGrpcServer(grpcPort)
	}

	if os.Getenv(DubboLog) != "" && os.Getenv(DubboProvider) != "" {
		// 启动Dubbo服务
		go dubbo.StartDubboServer()
	}
}

func InitClient() {
	if httpServerAddress := os.Getenv(HttpServer2Address); httpServerAddress != "" {
		// 配置HTTP客户端
		httpClient := http.InitHttpClient(httpServerAddress)
		api.ProtocolClients[CLIENT_HTTP] = httpClient
		api.HttpClient = httpClient
	}

	if grpcServerAddress := os.Getenv(GrpcServerAddress); grpcServerAddress != "" {
		// 配置客户端
		api.ProtocolClients[CLIENT_GRPC] = grpc.InitGrpcClient(grpcServerAddress)
	}

	if os.Getenv(DubboLog) != "" && os.Getenv(DubboConsumer) != "" {
		// 配置Dubbo客户端
		api.ProtocolClients[CLIENT_DUBBO] = dubbo.InitDubboClient()
	}
}
